<template>
  <div class="ai-research-container" >
    <!-- 任务表单卡片 -->
    <el-card class="task-form-card" v-if="!showHistoryTask">
      <template #header>
        <div class="card-header">
          <h2>AI行业研究任务</h2>
          <el-button
            type="text"
            @click="formCollapsed = !formCollapsed"
          >
            {{ formCollapsed ? '展开' : '收起' }}
            <el-icon class="collapse-icon">
              <ArrowDown v-if="!formCollapsed" />
              <ArrowUp v-else />
            </el-icon>
          </el-button>
        </div>
      </template>

      <el-collapse-transition>
        <div v-show="!formCollapsed">
          <el-form ref="taskFormRef" :model="taskForm" :rules="taskRules" label-width="120px">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="信息来源" prop="domain">
                  <el-select v-model="taskForm.domain" placeholder="请选择行业领域" style="width: 100%">
                    <el-option
                      v-for="item in industryDomains"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="模型选择" prop="model">
                  <el-select v-model="taskForm.model" placeholder="请选择AI模型" style="width: 100%">
                    <el-option
                      v-for="item in aiModels"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-form-item label="信息时效" required>
              <div class="date-range-container">
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-radio-group v-model="selectedDateRange" @change="handleDateRangeChange" style="width: 100%">
                      <el-radio-button label="3y">近3年</el-radio-button>
                      <el-radio-button label="1y">近1年</el-radio-button>
                      <el-radio-button label="6m">近6个月</el-radio-button>
                      <el-radio-button label="3m">近3个月</el-radio-button>
                      <el-radio-button label="custom">自定义</el-radio-button>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="12">
                    <div class="date-pickers-row">
                      <el-date-picker
                        v-model="taskForm.fromdate"
                        type="date"
                        placeholder="开始日期"
                        style="width: 45%"
                        format="YYYY-MM-DD"
                        value-format="YYYYMMDD"
                        :disabled="selectedDateRange !== 'custom'"
                        @change="handleCustomDateChange"
                      />
                      <span class="date-separator">-</span>
                      <el-date-picker
                        v-model="taskForm.todate"
                        type="date"
                        placeholder="结束日期"
                        style="width: 45%"
                        format="YYYY-MM-DD"
                        value-format="YYYYMMDD"
                        :disabled="selectedDateRange !== 'custom'"
                        :disabled-date="disableFutureDates"
                        @change="handleCustomDateChange"
                      />
                    </div>
                  </el-col>
                </el-row>
              </div>
            </el-form-item>

            <el-form-item label="研究模式" prop="deep">
              <el-radio-group v-model="taskForm.deep">
                <el-radio label="1">最快响应</el-radio>
                <el-radio label="2">深度研究</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="研究指令" prop="userInstruction">
              <el-input
                v-model="taskForm.userInstruction"
                type="textarea"
                :rows="4"
                placeholder="请输入您的研究需求，例如：分析金融科技行业的最新发展趋势和主要参与者..."
              />
              <div class="suggestion-container">
                <div class="suggestion-title">猜你想问：</div>
                <div class="suggestion-list">
                  <el-tag
                    v-for="(suggestion, index) in instructionSuggestions"
                    :key="index"
                    class="suggestion-tag"
                    @click="applyInstructionSuggestion(suggestion)"
                    type="info"
                    effect="plain"
                  >
                    {{ suggestion.shortText }}
                  </el-tag>
                </div>
              </div>
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="submitTaskForm" :loading="submitting">提交任务</el-button>
              <el-button @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-collapse-transition>
    </el-card>

    <!-- 任务结果卡片（包含任务状态） -->
    <el-card v-if="currentTaskId" class="task-result-card">
      <template #header>
        <div class="card-header">
          <h3>
            任务结果 (ID: {{ currentTaskId }})
            <el-tag v-if="taskResult && taskResult.status === 'in_progress'" type="warning" effect="dark">
              <span class="loading-dots">处理中</span>
            </el-tag>
            <el-tag v-else-if="taskResult && taskResult.status === 'completed'" type="success">已完成</el-tag>
            <el-tag v-else-if="taskResult && taskResult.status === 'failed'" type="danger">失败</el-tag>
          </h3>
          <div class="header-actions">
            <el-switch
              v-model="autoUpdateEnabled"
              active-text="自动更新"
              inactive-text="手动更新"
              @change="toggleAutoUpdate"
              style="margin-right: 15px;"
            />
            <el-button type="primary" link @click="refreshTaskResult">
              <el-icon class="refresh-icon"><Refresh /></el-icon> 刷新
            </el-button>
            <el-button type="text" @click="resultCollapsed = !resultCollapsed">
              {{ resultCollapsed ? '展开' : '收起' }}
              <el-icon class="collapse-icon">
                <ArrowDown v-if="!resultCollapsed" />
                <ArrowUp v-else />
              </el-icon>
            </el-button>
          </div>
        </div>
      </template>

      <el-collapse-transition>
        <div v-show="!resultCollapsed">
          <!-- 添加任务进度条 -->
          <div v-if="taskResult && taskResult.status === 'in_progress'" class="task-progress-container">
            <el-progress
              :percentage="calculateTaskProgress()"
              :status="taskResult.status === 'failed' ? 'exception' : ''"
              :stroke-width="15"
              :format="progressFormat"
            />
            <div class="progress-message">{{ getLatestStatusMessage() }}</div>
          </div>

          <!-- 任务状态详情折叠面板 -->
          <div class="status-panel">
            <div class="section-header">
              <h4>任务状态详情</h4>
              <div class="header-actions">
                <el-button type="primary" link @click="refreshTaskStatus" style="margin-right: 10px;">
                  <el-icon class="refresh-icon"><Refresh /></el-icon> 刷新状态
                </el-button>
                <el-button type="text" @click="statusCollapsed = !statusCollapsed">
                  {{ statusCollapsed ? '展开' : '收起' }}
                  <el-icon class="collapse-icon">
                    <ArrowDown v-if="statusCollapsed" />
                    <ArrowUp v-else />
                  </el-icon>
                </el-button>
              </div>
            </div>

            <el-collapse-transition>
              <div v-show="!statusCollapsed" class="status-content">
                <div v-if="taskStatusList && taskStatusList.length > 0">
                  <!-- 任务状态时间线 -->
                  <el-timeline>
                    <el-timeline-item
                      v-for="(status, index) in taskStatusList"
                      :key="index"
                      :type="getStatusType(status.nodeStatus)"
                      :color="getStatusColor(status.nodeStatus)"
                      :timestamp="formatTimestamp(status.timestamp)"
                    >
                      <el-card class="status-card">
                        <div class="status-content">
                          <p>{{ status.message || '无消息' }}</p>

                          <!-- Payload 展开/收起 -->
                          <div v-if="status.payload && Object.keys(status.payload).length > 0" class="payload-section">
                            <el-button type="text" @click="togglePayload(index)" class="toggle-payload-btn">
                              {{ expandedPayloads.includes(index) ? '收起' : '展开' }} Payload
                              <el-icon class="collapse-icon">
                                <ArrowDown v-if="!expandedPayloads.includes(index)" />
                                <ArrowUp v-else />
                              </el-icon>
                            </el-button>

                            <el-collapse-transition>
                              <div v-show="expandedPayloads.includes(index)" class="payload-content">
                                <el-descriptions :column="1" border>
                                  <el-descriptions-item
                                    v-for="(value, key) in status.payload"
                                    :key="key"
                                    :label="key"
                                  >
                                    {{ formatPayloadValue(value) }}
                                  </el-descriptions-item>
                                </el-descriptions>
                              </div>
                            </el-collapse-transition>
                          </div>
                        </div>
                      </el-card>
                    </el-timeline-item>
                  </el-timeline>
                </div>
                <div v-else class="no-data">
                  <el-empty description="任务执行中，暂无任务状态数据，请等待" />
                </div>
              </div>
            </el-collapse-transition>
          </div>

          <el-divider />

          <!-- 任务结果内容 -->
          <div v-if="taskResult" class="result-section">
            <el-descriptions title="任务信息" :column="1" border>
              <el-descriptions-item label="任务ID">{{ taskResult.taskId }}</el-descriptions-item>
              <el-descriptions-item label="任务状态">
                <el-tag :type="getStatusTagType(taskResult.status)">
                  {{ formatTaskStatus(taskResult.status) }}
                </el-tag>
              </el-descriptions-item>
            </el-descriptions>

            <div v-if="taskResult.outcome" class="task-outcome">
              <!-- 研究结果部分 -->
              <div class="section-header">
                <h4>研究结果</h4>
                <el-button type="text" @click="responseCollapsed = !responseCollapsed">
                  {{ responseCollapsed ? '展开' : '收起' }}
                  <el-icon class="collapse-icon">
                    <ArrowDown v-if="responseCollapsed" />
                    <ArrowUp v-else />
                  </el-icon>
                </el-button>
                </div>

              <el-collapse-transition>
                <div v-show="!responseCollapsed" class="response-content">
                  <markdown-renderer :content="taskResult.outcome.response" />
                </div>
              </el-collapse-transition>

              <!-- 元数据部分 -->
              <div v-if="taskResult.outcome.metadata" class="metadata-section">

                <el-collapse-transition>
                  <div v-show="!metadataCollapsed">
                    <el-descriptions :column="2" border>
                      <el-descriptions-item v-if="taskResult.outcome.metadata.stockCode" label="股票代码">
                        {{ taskResult.outcome.metadata.stockCode }}
                      </el-descriptions-item>
                      <el-descriptions-item v-if="taskResult.outcome.metadata.fromDate" label="开始日期">
                        {{ formatDate(taskResult.outcome.metadata.fromDate) }}
                      </el-descriptions-item>
                      <el-descriptions-item v-if="taskResult.outcome.metadata.toDate" label="结束日期">
                        {{ formatDate(taskResult.outcome.metadata.toDate) }}
                      </el-descriptions-item>
                    </el-descriptions>
                  </div>
                </el-collapse-transition>

                <!-- 相关公告部分 -->
                <div v-if="taskResult.outcome.metadata.announcements && taskResult.outcome.metadata.announcements.length > 0" class="announcements-section">
                  <div class="section-header">
                    <h4>相关公告</h4>
                    <el-button type="text" @click="announcementsCollapsed = !announcementsCollapsed">
                      {{ announcementsCollapsed ? '展开' : '收起' }}
                      <el-icon class="collapse-icon">
                        <ArrowDown v-if="announcementsCollapsed" />
                        <ArrowUp v-else />
                      </el-icon>
                    </el-button>
                  </div>

                  <el-collapse-transition>
                    <div v-show="!announcementsCollapsed">
                      <el-table :data="taskResult.outcome.metadata.announcements" style="width: 100%">
                        <el-table-column prop="TITLE" label="标题" />
                        <el-table-column prop="DATE_TIME" label="日期" width="120" />
                        <el-table-column label="操作" width="80">
                          <template #default="scope">
                            <el-button type="primary" link @click="openUrl(scope.row.FILE_LINK)">查看</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </div>
                  </el-collapse-transition>
                </div>

                <!-- 解析内容部分 -->
                <div v-if="taskResult.outcome.metadata.parsedContents && taskResult.outcome.metadata.parsedContents.length > 0" class="parsed-contents-section">
                  <div class="section-header">
                    <h4>解析内容</h4>
                    <el-button type="text" @click="parsedContentsCollapsed = !parsedContentsCollapsed">
                      {{ parsedContentsCollapsed ? '展开' : '收起' }}
                      <el-icon class="collapse-icon">
                        <ArrowDown v-if="parsedContentsCollapsed" />
                        <ArrowUp v-else />
                      </el-icon>
                    </el-button>
                    </div>

                  <el-collapse-transition>
                    <div v-show="!parsedContentsCollapsed">
                      <el-table :data="taskResult.outcome.metadata.parsedContents" style="width: 100%">
                        <el-table-column prop="type" label="类型" width="180" />
                        <el-table-column prop="name" label="名称" />
                        <el-table-column prop="value" label="值" width="180" />
                      </el-table>
                    </div>
                  </el-collapse-transition>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="no-data">
            <el-empty description="暂无任务结果数据" />
          </div>
        </div>
      </el-collapse-transition>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, ArrowUp, Refresh } from '@element-plus/icons-vue'
import {
  submitTask,
  getTaskOutcome,
  getMockTaskOutcome,
  checkTaskStatus,
  getMockTaskStatus, downloadPDF, generateTaskPDF
} from '../../api/aiResearch'
import { getIndustryDomainList } from '../../api/industryDomain'
import MarkdownRenderer from '../../components/MarkdownRenderer.vue'
import dayjs from 'dayjs'
import { useRoute } from 'vue-router'
import {useCounterStore } from '../../stores/counter.js'

// 表单引用
const taskFormRef = ref(null)
const route = useRoute()

// 折叠状态控制
const formCollapsed = ref(false)
const resultCollapsed = ref(false)
const responseCollapsed = ref(false)
const metadataCollapsed = ref(false)
const announcementsCollapsed = ref(false)
const parsedContentsCollapsed = ref(false)
const statusCollapsed = ref(true)

// 日期范围选择
const selectedDateRange = ref('6m') // 默认选择近6个月

// 日期范围预设
const dateRangePresets = {
  '3y': { months: 36 },
  '1y': { months: 12 },
  '6m': { months: 6 },
  '3m': { months: 3 },
  'custom': null
}

// 行业领域选项
const industryDomains = ref([])

// 任务表单
const taskForm = reactive({
  domain: 'hkex', // 默认为港交所
  model: 'qwen-turbo-latest', // 默认为千问
  fromdate: '',
  todate: '',
  deep: '2',
  userInstruction: '',
  timestamp: ''
})

// AI模型选项
const aiModels = ref([
  { value: 'qianwen', label: '通义千问' },
  { value: 'gpt4', label: 'GPT-4' },
  { value: 'claude', label: 'Claude' },
  { value: 'llama', label: 'Llama' }
])

// 表单验证规则
const taskRules = {
  domain: [{ required: true, message: '请选择行业领域', trigger: 'change' }],
  model: [{ required: true, message: '请选择AI模型', trigger: 'change' }],
  fromdate: [{ required: true, message: '请选择开始日期', trigger: 'change' }],
  todate: [{ required: true, message: '请选择结束日期', trigger: 'change' }],
  deep: [{ required: true, message: '请选择研究深度', trigger: 'change' }],
  userInstruction: [{ required: true, message: '请输入研究指令', trigger: 'blur' }]
}
//
const showHistoryTask = ref(false)
// 提交状态
const submitting = ref(false)

// 当前任务ID
const currentTaskId = ref('')

// 任务结果
const taskResult = ref(null)

// 任务状态
const taskStatus = ref(null)

// 任务状态列表
const taskStatusList = ref([])

// 展开的payload索引
const expandedPayloads = ref([])

// 自动更新相关
const autoUpdateInterval = ref(null)
const autoUpdateEnabled = ref(true)
const updateIntervalTime = 5000 // 5秒更新一次
const maxPollCount = 50 // 最大轮询次数
const pollCount = ref(0) // 当前轮询次数


const store = useCounterStore();

// 计算今天的日期（格式：YYYYMMDD）
const today = computed(() => {
  return dayjs().format('YYYYMMDD')
})

// 禁用未来日期
const disableFutureDates = (date) => {
  return date > dayjs().endOf('day')
}

// 处理日期范围变化
const handleDateRangeChange = (value) => {
  if (value === 'custom') {
    // 自定义模式不自动设置日期
    return
  }

  const preset = dateRangePresets[value]
  if (preset) {
    // 设置结束日期为今天
    taskForm.todate = today.value

    // 根据选择的时间范围计算开始日期
    taskForm.fromdate = dayjs()
      .subtract(preset.months, 'month')
      .format('YYYYMMDD')
  }
}

// 处理自定义日期变化
const handleCustomDateChange = () => {
  // 如果用户手动修改了日期，切换到自定义模式
  if (taskForm.fromdate && taskForm.todate) {
    selectedDateRange.value = 'custom'
  }
}

// 获取行业领域列表
const fetchIndustryDomains = async () => {
  try {
    const res = await getIndustryDomainList()
    if (res.code === 200) {
      industryDomains.value = res.data.map(item => ({
        value: item.industryDomainId.toString(),
        label: item.industryDomainName
      }))
    }
  } catch (error) {
    console.error('获取行业领域失败', error)
    // 使用模拟数据
    industryDomains.value = [
      { value: 'hkex', label: '港交所' },
      { value: 'sse', label: '上交所' },
      { value: 'szse', label: '深交所' },
      { value: 'finance', label: '金融服务' },
      { value: 'tech', label: '信息技术' }
    ]
  }
}

// 提交任务表单
const submitTaskForm = () => {
  taskFormRef.value.validate(async (valid) => {
    if (!valid) return

    submitting.value = true
    try {
      // 添加时间戳
      taskForm.timestamp = new Date().toISOString()

      // 调用API提交任务
      const res = await submitTask(taskForm)

      if (res.code === 200) {
        ElMessage.success('任务提交成功')
        currentTaskId.value = res.data.taskId

        // 重置轮询计数
        pollCount.value = 0

        // 获取任务状态和结果
        fetchTaskStatus()
        fetchTaskResult()
        console.log("提交任务，启动自动更新")
        // 启动自动更新
        startAutoUpdate()

        // 通知更新历史记录
        store.increment();

        // 自动收起表单，展开结果
        formCollapsed.value = true
        resultCollapsed.value = false
        statusCollapsed.value = false
      } else {
        ElMessage.error(res.message || '任务提交失败')
      }
    } catch (error) {
      ElMessage.error(res.message || '任务提交失败')
    } finally {
      submitting.value = false
    }
  })
}

// 重置表单
const resetForm = () => {
  taskFormRef.value.resetFields()
  // 重置日期范围选择为默认值
  selectedDateRange.value = '6m'
  // 重新设置默认日期范围
  handleDateRangeChange('6m')
}

// 获取任务结果
const fetchTaskResult = async () => {
  if (!currentTaskId.value) return

  try {
    const res = await getTaskOutcome(currentTaskId.value)
    if (res.code === 200) {
      taskResult.value = res.data

      // 如果状态是完成，展开研究结果并停止自动更新
      if (res.data.status === 'completed') {
        responseCollapsed.value = false
        stopAutoUpdate()
        ElMessage.success('任务已完成')
      }
    } else {
      ElMessage.error(res.message || '获取任务结果失败')
    }
  } catch (error) {
    ElMessage.error(res.message || '获取任务结果失败')
  }
}

// 获取模拟任务结果
const fetchMockTaskResult = async () => {
  try {
    const res = await getMockTaskOutcome(currentTaskId.value)
    taskResult.value = res.data

    // 如果状态是完成，展开研究结果并停止自动更新
    if (res.data.status === 'completed') {
      responseCollapsed.value = false
      stopAutoUpdate()
      ElMessage.success('任务已完成')
    }
  } catch (error) {
    console.error('获取模拟任务结果失败', error)
  }
}

// 获取任务状态
const fetchTaskStatus = async () => {
  if (!currentTaskId.value) return

  // 增加轮询计数
  pollCount.value++

  // 检查是否超过最大轮询次数
  if (pollCount.value > maxPollCount) {
    ElMessage.warning(`已达到最大轮询次数(${maxPollCount})，停止自动更新`)
    stopAutoUpdate()
    return
  }

  try {
    const res = await checkTaskStatus(currentTaskId.value)
    if (res.code === 200) {
      taskStatusList.value = res.data.data || []

      // 更新任务状态
      if (taskStatusList.value.length > 0) {
        const lastStatus = taskStatusList.value[taskStatusList.value.length - 1]
        taskStatus.value = {
          status: lastStatus.overallStatus,
          progress: calculateProgress(taskStatusList.value),
          message: lastStatus.message
        }
      }
    } else {
      ElMessage.error(res.message || '获取任务状态失败')
    }
  } catch (error) {
    ElMessage.error(res.message || '获取任务状态失败')
  }
}

// 计算任务进度
const calculateProgress = (statusList) => {
  if (!statusList || statusList.length === 0) return 0

  // 计算已完成的步骤数
  const completedSteps = statusList.filter(item => item.nodeStatus === 'completed').length

  // 计算进度百分比
  return Math.round((completedSteps / statusList.length) * 100)
}

// 获取模拟任务状态
const fetchMockTaskStatus = async () => {
  try {
    // 模拟数据
    const mockStatusList = [
      {
        taskId: currentTaskId.value,
        stepId: 1,
        overallStatus: 'in_progress',
        currentNode: '任务初始化',
        nodeStatus: 'completed',
        message: '任务已成功初始化',
        timestamp: new Date(Date.now() - 300000).toISOString(),
        payload: {
          domain: taskForm.domain,
          fromDate: taskForm.fromdate,
          toDate: taskForm.todate
        }
      },
      {
        taskId: currentTaskId.value,
        stepId: 2,
        overallStatus: 'in_progress',
        currentNode: '数据收集',
        nodeStatus: 'in_progress',
        message: '正在收集行业数据...',
        timestamp: new Date(Date.now() - 180000).toISOString(),
        payload: {
          dataSource: '公开数据',
          progress: '45%'
        }
      }
    ]

    // 随机添加一个正在进行的步骤
    if (Math.random() > 0.5) {
      mockStatusList.push({
        taskId: currentTaskId.value,
        stepId: 3,
        overallStatus: 'in_progress',
        currentNode: '数据分析',
        nodeStatus: 'pending',
        message: '等待数据分析...',
        timestamp: new Date().toISOString(),
        payload: {
          waitingFor: '数据收集完成'
        }
      })
    }

    taskStatusList.value = mockStatusList

    // 更新任务状态
    if (taskStatusList.value.length > 0) {
      const lastStatus = taskStatusList.value[taskStatusList.value.length - 1]
      taskStatus.value = {
        status: lastStatus.overallStatus,
        progress: calculateProgress(taskStatusList.value),
        message: lastStatus.message
      }
    }
  } catch (error) {
    console.error('获取模拟任务状态失败', error)
  }
}

// 启动自动更新
const startAutoUpdate = (isMock = false) => {
  // 先停止现有的自动更新
  stopAutoUpdate()

  // 重置轮询计数
  pollCount.value = 0

  // 立即检查一次状态和结果
  if (isMock) {
    fetchMockTaskStatus()
    fetchMockTaskResult()
  } else {
    fetchTaskStatus()
    fetchTaskResult()
  }

  // 设置定时器，定期检查状态和结果
  autoUpdateInterval.value = setInterval(() => {
    if (autoUpdateEnabled.value) {
      if (isMock) {
        fetchMockTaskStatus()
        fetchMockTaskResult()
      } else {
        fetchTaskStatus()
        fetchTaskResult()
      }
    }
  }, updateIntervalTime)
}

// 停止自动更新
const stopAutoUpdate = () => {
  if (autoUpdateInterval.value) {
    clearInterval(autoUpdateInterval.value)
    autoUpdateInterval.value = null
  }
}

// 切换自动更新状态
const toggleAutoUpdate = () => {
  if (autoUpdateEnabled.value) {
    startAutoUpdate()
  } else {
    stopAutoUpdate()
  }

  ElMessage.info(autoUpdateEnabled.value ? '已启用自动更新' : '已禁用自动更新')
}

// 手动刷新任务状态
const refreshTaskStatus = () => {
  fetchTaskStatus()
}

// 手动刷新任务结果
const refreshTaskResult = () => {
  fetchTaskResult()
}

// 切换Payload展开状态
const togglePayload = (index) => {
  const position = expandedPayloads.value.indexOf(index)
  if (position === -1) {
    expandedPayloads.value.push(index)
  } else {
    expandedPayloads.value.splice(position, 1)
  }
}

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return ''

  try {
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    return timestamp
  }
}

// 格式化节点状态
const formatNodeStatus = (status) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'in_progress':
      return '进行中'
    case 'pending':
      return '等待中'
    case 'failed':
      return '失败'
    default:
      return status || '未知'
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'in_progress':
      return 'warning'
    case 'pending':
      return 'info'
    case 'failed':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取状态颜色
const getStatusColor = (status) => {
  switch (status) {
    case 'completed':
      return '#67C23A'
    case 'progressing':
      return '#E6A23C'
    case 'pending':
      return '#909399'
    case 'failed':
      return '#F56C6C'
    default:
      return '#909399'
  }
}

// 获取状态标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case 'completed':
      return 'success'
    case 'in_progress':
      return 'warning'
    case 'pending':
      return 'info'
    case 'failed':
      return 'danger'
    default:
      return 'info'
  }
}

// 格式化Payload值
const formatPayloadValue = (value) => {
  if (value === null || value === undefined) {
    return '无'
  }

  if (typeof value === 'object') {
    return JSON.stringify(value)
  }

  return value.toString()
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''

  // 如果日期格式为YYYYMMDD，转换为YYYY-MM-DD
  if (dateStr.length === 8) {
    return `${dateStr.substring(0, 4)}-${dateStr.substring(4, 6)}-${dateStr.substring(6, 8)}`
  }

  return dateStr
}

// 格式化任务状态
const formatTaskStatus = (status) => {
  switch (status) {
    case 'completed':
      return '已完成'
    case 'in_progress':
      return '进行中'
    case 'pending':
      return '等待中'
    case 'failed':
      return '失败'
    default:
      return status
  }
}

// 打开URL
const openUrl = (url) => {
  if (!url) return
  const baseUrl = 'https://www1.hkexnews.hk' //港交所的域名，后续需要根据信息来源字段更换
  window.open(baseUrl+url, '_blank');

}

// 监听任务ID变化
watch(currentTaskId, (newVal) => {
  console.log("监听到任务ID变化")
  console.log(showHistoryTask.value);
  if (newVal) {
    console.log("有新的任务ID，是否历史记录"+showHistoryTask.value)

    if(showHistoryTask.value){
      console.log("历史记录无需更新")
      stopAutoUpdate()
    }else {
      startAutoUpdate()
    }
  } else {
    // 如果任务ID被清空，停止自动更新
    console.log("任务ID被清空，停止自动更新")
    stopAutoUpdate()
  }
})
// 监听特定参数变化（如 id）
watch(
    () => route.query.taskId,
    (newId, oldId) => {
      console.log('参数变化:', newId, oldId);
      if(newId !== null){
        showHistoryTask.value = true
      }
      if(newId === undefined){
        showHistoryTask.value = false
      }
      console.log(showHistoryTask.value)
      currentTaskId.value = newId;
      fetchTaskStatus()
      fetchTaskResult()
    }
);
// 监听任务结果变化
watch(() => taskResult.value?.status, (newStatus) => {
  if (newStatus === 'completed') {
    // 如果任务完成，停止自动更新
    stopAutoUpdate()
    ElMessage.success('任务已完成')
  }
})

// 组件挂载时获取数据
onMounted(() => {
  fetchIndustryDomains()

  // 设置默认日期范围（近6个月）
  handleDateRangeChange(selectedDateRange.value)

  // 如果有任务ID，启动自动更新
  if (currentTaskId.value) {
    startAutoUpdate()
  }
})

// 组件卸载时清理
onUnmounted(() => {
  stopAutoUpdate()
})

// 指令建议列表
const instructionSuggestions = ref([
  {
    shortText: 'twobu财报分析',
    fullText: '工商银行 01398 2025第一季度财报解析，要求尽量详细，与图表的形式展示'
  },
  {
    shortText: '四大银行财报对比分析',
    fullText: '请分析工商银行、建设银行、中国银行、农业银行的财报，并且给出一份详细的财报分析对比报告，要求内容详实，图文并茂'
  },
  {
    shortText: '银行行业竞争格局分析',
    fullText: '内容搜索，请分析该银行行业的竞争格局，包括主要参与者、市场份额、竞争优势和劣势，以及未来可能的竞争策略变化。'
  },
  {
    shortText: '金融行业政策法规影响',
    fullText: '内容搜索，请分析近期新闻相关政策法规变化对金融行业的影响，包括机遇和挑战，以及企业可能采取的应对策略。',
    domain: 'cls'
  },
  {
    shortText: '投资风险评估',
    fullText: '内容搜索，请评估投资该行业/公司的主要风险因素，包括市场风险、政策风险、财务风险和运营风险，并提供风险缓解建议。',
    domain: 'cls'
  },
  {
    shortText: '俄乌冲突对全球金融业的影响',
    fullText: '内容搜索，分析俄乌冲突对全球金融市场的影响，包括对银行业、资本市场、汇率和大宗商品价格的冲击，以及中国金融机构应对策略。',
    domain: 'cls' // 自动选择财联社作为信息来源
  }
])

// 应用指令建议
const applyInstructionSuggestion = (suggestion) => {
  // 填充研究指令
  taskForm.userInstruction = suggestion.fullText

  // 如果建议中包含指定的信息来源，则自动选择
  if (suggestion.domain) {
    taskForm.domain = suggestion.domain

    // 如果表单已折叠，则展开它以显示选择的信息来源
    if (formCollapsed.value) {
      formCollapsed.value = false
    }
  }

  // 滚动到表单区域，提高用户体验
  nextTick(() => {
    document.querySelector('.task-form-card').scrollIntoView({ behavior: 'smooth' })
  })
}

// 计算任务总体进度
const calculateTaskProgress = () => {
  if (!taskStatusList.value || taskStatusList.value.length === 0) {
    return 0
  }

  // 计算已完成的步骤数
  const completedSteps = taskStatusList.value.filter(item =>
    item.nodeStatus === 'completed').length

  // 计算总步骤数
  const totalSteps = taskStatusList.value.length

  // 计算进行中的步骤的部分进度
  const inProgressStep = taskStatusList.value.find(item =>
    item.nodeStatus === 'in_progress')

  let inProgressPercentage = 0
  if (inProgressStep && inProgressStep.payload && inProgressStep.payload.progress) {
    // 尝试从payload中获取进度
    const progressStr = inProgressStep.payload.progress
    const match = progressStr.match(/(\d+)%/)
    if (match && match[1]) {
      inProgressPercentage = parseInt(match[1]) / 100
    } else {
      // 默认进行中的步骤完成了50%
      inProgressPercentage = 0.5
    }
  } else if (inProgressStep) {
    // 默认进行中的步骤完成了50%
    inProgressPercentage = 0.5
  }

  // 计算总进度
  const progress = ((completedSteps + inProgressPercentage) / totalSteps) * 100

  // 确保进度在0-100之间
  return Math.min(Math.max(Math.round(progress), 0), 100)
}

// 进度条格式化函数
const progressFormat = (percentage) => {
  return percentage === 100 ? '完成' : `${percentage}%`
}

// 获取最新的状态消息
const getLatestStatusMessage = () => {
  if (!taskStatusList.value || taskStatusList.value.length === 0) {
    return '正在初始化任务...'
  }

  // 获取最新的状态消息
  const latestStatus = taskStatusList.value[taskStatusList.value.length - 1]
  return latestStatus.message || '正在处理...'
}

//
const download = async () =>{
  try {
    await generateTaskPDF(currentTaskId.value)
  }catch (error) {
    console.error('生成pdf报告失败', error)
  }
  try {
     await downloadPDF(currentTaskId.value)
  }catch (error) {
    console.error('下载pdf报告失败', error)
  }

}
</script>

<style scoped>
.ai-research-container {
  padding: 20px;
}

.task-form-card,
.task-result-card {
  margin-bottom: 20px;
}

/* 日期范围容器样式 */
.date-range-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.date-presets {
  margin-bottom: 10px;
}

.date-pickers {
  display: flex;
  align-items: center;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 10px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  margin-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 10px;
}

.collapse-icon {
  margin-left: 5px;
}

.text-center {
  text-align: center;
}

.status-card {
  margin-bottom: 15px;
}

.status-panel {
  background-color: #f8f9fa;
  border-radius: 4px;
  padding: 10px 15px;
  margin: 15px 0;
}

.status-content {
  padding: 10px 0;
}

.payload-section {
  margin-top: 10px;
}

.toggle-payload-btn {
  margin: 5px 0;
}

.payload-content {
  margin-top: 10px;
  background-color: #fff;
  border-radius: 4px;
  padding: 10px;
}

.task-outcome {
  margin-top: 20px;
}

.response-content {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 4px;
  margin: 10px 0;
  white-space: pre-line;
}

.metadata-section,
.announcements-section,
.parsed-contents-section {
  margin-top: 20px;
}

.no-data {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}

.refresh-icon {
  margin-right: 5px;
}

.result-section {
  margin-top: 20px;
}

.task-status {
  margin: 15px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .date-range-container {
    flex-direction: column;
  }

  .date-presets {
    margin-bottom: 15px;
    overflow-x: auto;
  }

  .date-presets .el-radio-group {
    white-space: nowrap;
  }

  .date-pickers {
    width: 100%;
  }

  .header-actions {
    flex-direction: column;
    align-items: flex-end;
    gap: 5px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .section-header .header-actions {
    margin-top: 10px;
    width: 100%;
    flex-direction: row;
    justify-content: flex-end;
  }
}

.suggestion-container {
  margin-top: 10px;
}

.suggestion-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
}

.suggestion-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.suggestion-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.suggestion-tag:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}
</style>
